package com.road.crawler.meizitu.crawler;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.geccocrawler.gecco.pipeline.Pipeline;
import com.geccocrawler.gecco.request.HttpRequest;
import com.geccocrawler.gecco.scheduler.SchedulerContext;
import com.road.crawler.meizitu.model.CategoryType;
import com.road.crawler.meizitu.service.CategoryTypeService;

/**
 * @Description :
 * @Author :WeiHui.Zhang
 * @Data : 2016/3/30 10:51
 * @Version:1.0.0
 */
@Service
public class SaveCategoryPipeline implements Pipeline<IndexPage> {

	@Resource(name="categoryTypeServiceImpl")
	private CategoryTypeService categoryTypeService;

	@Override
	public void process(IndexPage bean) {
		// 获得首页分类
		List<CategoryType> categoryTypes = bean.getCategoryTypes();
		
		// 获取数据库分类
		List<CategoryType> categoryTypesDB = categoryTypeService.findAll();
		for (CategoryType categoryType : categoryTypes) {
			CategoryType c = categoryTypesDB.stream().filter(f -> f.getTag().equals(f.getTag())).findFirst().orElse(null);
			if (null == c) {
				// 首页分类入库
				categoryTypeService.save(categoryType);
			} else {
				c = categoryType;
			}
			
			// 解析分类页面数据
			HttpRequest sub = bean.getRequest().subRequest(c.getUrl());
			sub.addParameter("tagId", "" + c.getId());
			sub.addParameter("currPage", "1");
			SchedulerContext.into(sub);
		}
	}
}
